<?php

/**
 * 修改config的函数
 * @param $arr1 配置前缀
 * @param $arr2 数据变量
 * @return bool 返回状态
 */
function setconfig($pat, $rep)
{
	/**
	 * 原理就是 打开config配置文件 然后使用正则查找替换 然后在保存文件.
	 * 传递的参数为2个数组 前面的为配置 后面的为数值.  正则的匹配为单引号  如果你的是分号 请自行修改为分号
	 * $pat[0] = 参数前缀;  例:   default_return_type
	   $rep[0] = 要替换的内容;    例:  json
	 */
	$fileurl = APP_PATH . "/Home/Conf/config.php";
	$string = file_get_contents($fileurl); //加载配置文件
	$fp = fopen($fileurl, "r+");
  
	
	
	
	if (flock($fp, LOCK_EX)) {  // 进行排它型锁定  
		
		$pats[0] = '/\'' . $pat . '\'(.*?),/';
		$reps[0] = "'". $pat. "'". "=>" . "'".$rep ."',";
		
		
		//$string = fread($fp,filesize($fileurl));
		//$string = fpassthru($fp);
		$string = preg_replace($pats, $reps, $string); // 正则查找然后替换
		//echo $string;
	
		fwrite($fp,$string); // 写入配置文件
		
		flock($fp, LOCK_UN);    // 释放锁定  
	} else {  
		echo "文件正在被其他程序占用";  
	}  
	   
	
    fclose($fp);
	return true;
	
}

/*
 * 删除缓存方法
 */
function delFileByDir($dir) {
	$dh = opendir($dir);
	while ($file = readdir($dh)) {
		if ($file != "." && $file != "..") {

			$fullpath = $dir . "/" . $file;
			if (is_dir($fullpath)) {
				delFileByDir($fullpath);
			} else {
				unlink($fullpath);
			}
		}
	}
	closedir($dh);
}


/**
 * 判断是否在微信浏览器中打开
 * @return boolean
 */
function is_weixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

    /**
     * 判断是移动设备访问
     */
function is_mobile() {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset($_SERVER['HTTP_VIA'])) {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }

/*根据id获取头像
 * */
function get_nickname($userid){
	$userinfo = M('user')->where("id = $userid")->find();
	if($userinfo['nickname']){
		return $userinfo['nickname'];
	}else{
		return false;
	}
} 
function kefuurl(){
    $info = M('config')->find(7);
    if ($info)
    {return $info['kefu'];}
    else{
        return 0;
    }

}
/*post请求获取数据*/
function curlPost($url, $timeout = 5) {
	if (function_exists('file_get_contents')) {
		$optionget = array('http' => array('method' => "GET", 'header' => "User-Agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.0.04506; CIBA)\r\nAccept:*/*\r\nReferer:https://kyfw.12306.cn/otn/lcxxcx/init"));
		$file_contents = file_get_contents($url, false, stream_context_create($optionget));
	} else {
		$ch = curl_init();
		$header = array('Accept:*/*', 'Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding:gzip,deflate,sdch', 'Accept-Language:zh-CN,zh;q=0.8,ja;q=0.6,en;q=0.4', 'Connection:keep-alive', 'Host:kyfw.12306.cn', 'Referer:https://kyfw.12306.cn/otn/lcxxcx/init', );
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$file_contents = curl_exec($ch);
		curl_close($ch);
	}
	$file_contents = json_decode($file_contents, true);
	return $file_contents;
}
/*get请求获取数据*/
function curlGet($url){
	$ch = curl_init();
	//设置选项，包括URL
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
    if (strpos($url, 'https') !== false) {
        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    }
	//执行并获取HTML文档内容
	$output = curl_exec($ch);
	//释放curl句柄
	curl_close($ch);
	return $output;
}

    function http_get($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, trim($url));
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // 获取的信息以文件流的形式返回
        // curl_setopt($ch,CURLOPT_USERAGENT, $user_agent);

//        curl_setopt($ch, CURLOPT_HEADER, $return_header); // 显示返回的Header区域内容
	    if (strpos($url, 'https') !== false) {
	        // curl_setopt($ch, CURLOPT_SSLVERSION, 3);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	    }
        curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 设置超时限制防止死循环
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            $result = curl_error($ch);  // 捕抓异常
        }
        return $result;
    }

	function https_get($url) {
		$header = array( //头部信息，上面的函数已说明
			'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
			'Accept-Charset:text/html,application/xhtml+xml,application/xml;q=0.7,*;q=0.3',
			'Accept-Encoding:gzip, deflate, br',
			'Accept-Language:zh-CN,zh;q=0.9',
			'Connection:keep-alive',
			'Content-Type:application/json; charset=utf-8',
			'Host: www.1396j.com',
			'Upgrade-Insecure-Requests: 1',
		);
		$user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1';
		$curl = curl_init(); // 启动一个CURL会话
		curl_setopt($curl, CURLOPT_URL, $url);
//		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		if (strpos($url, 'https') !== false) {
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);//对认证证书来源的检查，不开启次功能
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//从证书中检测 SSL 加密算法
			curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
			curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		}
//		curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
		//模拟用户使用的浏览器，自己设置，我的是"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0"
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);//自动设置referer
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($curl);     //返回api的json对象
		if (curl_errno($curl)) {
			$result = curl_error($curl);  // 捕抓异常
		}
		//关闭URL请求
		curl_close($curl);
		return $result;
	}
/**
 *
 * @param $url     网址
 * @param $Referer 来路设置
 * @param $timeout 链接超时时长
 */

function sockget($url,$Referer=1,$timeout=5){
	 $info = parse_url($url);
	 $fp = fsockopen($info['host'], 80);
	if(!$fp) {
		die('无法连接');
               //echo "$errstr ($errno)&lt;br&gt;\n";
	} else {		
	stream_set_blocking($fp,0);//开启非阻塞模式 
	
		stream_set_timeout($fp, 5);  //读取超时
		$end = "\r\n";
	         $head = "GET ".$info['path'].($info["query"]?'?'.$info['query']:'')." HTTP/1.1$end";
		$head .= "Host: ".$info['host']."$end";
		//伪造来路页面
		$head .= "Referer: https://".$info['host'].($Referer!=1?$info['path'].($info["query"]?'?'.$info['query']:''):'')."$end";
		$head.="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)$end";
		$head .= "Connection: Close$end";
		$head .= "$end";

  		// echo $head;
  		// exit;
		fputs($fp,$head);
		$info = stream_get_meta_data($fp);//获取读取内容是否超时
		
	 	if ($info['timed_out']) {
	 		 fclose($fp);
        	         echo 'Connection timed out!';
        	         die('发送数据超时');
    	         }
	       $content='';
                while(!feof($fp) && (!$info['timed_out'])) {
                $content.=fgets($fp,1024);
                $info = stream_get_meta_data($fp);
                flush(); 
        }
        fclose($fp);
        if ($info['timed_out']) {
        die('读取数据 Connection timed out!');
    	}

        return $content;
      }
}

function get__browser() {
	// 默认为 chrome 标准浏览器
	$browser = array(
		'device'=>'pc', // pc|mobile|pad
		'name'=>'chrome', // chrome|firefox|ie|opera
		'version'=>30,
	);
	$agent = $_SERVER['HTTP_USER_AGENT'];
	// 主要判断是否为垃圾 IE6789
	if(strpos($agent, 'msie') !== FALSE || stripos($agent, 'trident') !== FALSE) {
		$browser['name'] = 'ie';
		$browser['version'] = 8;
		preg_match('#msie\s*([\d\.]+)#is', $agent, $m);
		if(!empty($m[1])) {
			if(strpos($agent, 'compatible; msie 7.0;') !== FALSE) {
				$browser['version'] = 8;
			} else {
				$browser['version'] = intval($m[1]);
			}
		} else {
			// 匹配兼容模式 Trident/7.0，兼容模式下会有此标志 $trident = 7;
			preg_match('#Trident/([\d\.]+)#is', $agent, $m);
			if(!empty($m[1])) {
				$trident = intval($m[1]);
				$trident == 4 AND $browser['version'] = 8;
				$trident == 5 AND $browser['version'] = 9;
				$trident > 5 AND $browser['version'] = 10;
			}
		}
	}

	if(isset($_SERVER['HTTP_X_WAP_PROFILE']) || (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap") || stripos($agent, 'phone')  || stripos($agent, 'mobile') || strpos($agent, 'ipod'))) {
		$browser['device'] = 'mobile';
	} elseif(strpos($agent, 'pad') !== FALSE) {
		$browser['device'] = 'pad';
		$browser['name'] = '';
		$browser['version'] = '';
	/*
	} elseif(strpos($agent, 'miui') !== FALSE) {
		$browser['device'] = 'mobile';
		$browser['name'] = 'xiaomi';
		$browser['version'] = '';
	*/
	} else {
		$robots = array('bot', 'spider', 'slurp');
		foreach($robots as $robot) {
			if(strpos($agent, $robot) !== FALSE) {
				$browser['name'] = 'robot';
				return $browser;
			}
		}
	}
	return $browser;
}

/*
 * （百家乐）根据开的牌返回得奖方案
 */
function dejiang($a=''){
//    $a='{"庄":[["黑","9"],["黑","k"],["黑","q"]],"闲":[["黑","2"],["黑","2"]]}';//开奖数据
    $a=json_decode($a,1);
    //计算累加值
    $zhuang=0;//庄
    $xian=0;//闲
    foreach ($a['庄'] as $v){//累加
        $val=$v[1];
        if ('A'==$val){$val=1;}
        else if ('10'==$val||'J'==$val||'Q'==$val||'K'==$val||!(stristr('23456789',$val))){$val=0;}
        $zhuang+=$val;
    }
    foreach ($a['闲'] as $v){//累加
        $val=$v[1];
        if ('A'==$val){$val=1;}
        else if ('10'==$val||'J'==$val||'Q'==$val||'K'==$val||!(stristr('23456789',$val))){$val=0;}
        $xian+=$val;
    }
    $zhuang=$zhuang%10;//最后值
    $xian=$xian%10;


    $dejiang=[];//得奖集合
    //1.判断大小(庄闲和)
    if ($zhuang>$xian){array_push($dejiang,1); }
    elseif ($zhuang<$xian){array_push($dejiang,2);}
    elseif ($zhuang==$xian){array_push($dejiang,3);array_push($dejiang,7);}//和 三宝

    //2.对子 庄对 闲对
    if ($a['庄'][0][1]==$a['庄'][1][1]){
        array_push($dejiang,4);array_push($dejiang,6);array_push($dejiang,7);//庄对 对子 三宝
    }
    if ($a['闲'][0][1]==$a['闲'][1][1]){
        array_push($dejiang,5);array_push($dejiang,6);array_push($dejiang,7);//闲对 对子 三宝
    }

//    $ff=zhongjiang_fanyi($dejiang);
    return $dejiang;
}
/*
 * （百家乐）根据开的牌返回得奖方案
 */
function dejiang_lh($a=''){
//    $a='{"龙":[["黑","5"]],"虎":[["黑","A"]]}';//（大-》小  黑红花片）开奖数据
    $a=json_decode($a,1);
    //计算累加值
    $huase=['黑'=>0.4,'红'=>0.3,'花'=>0.2,'片'=>0.1,];//花色拟定
    $shuzi=['A'=>'1','J'=>'11','Q'=>'12','K'=>'13'];//扑克字符
    //龙
    if (in_array($a['龙'][1],['A','J','Q','K'])){
        $long=$shuzi[$a['龙'][1]];
    }else{
        $long=$a['龙'][1];
    }
    $long+=$huase[$a['龙'][0]];
    //虎
    if (in_array($a['虎'][1],['A','J','Q','K'])){
        $hu=$shuzi[$a['虎'][1]];
    }else{
        $hu=$a['虎'][1];
    }
    $hu+=$huase[$a['虎'][0]];
    //1.判断大小(庄闲和)
    if ($long>$hu){$dejiang=1;}
    elseif ($long<$hu){$dejiang=2;}
    elseif ($long==$hu){$dejiang=3;}//和

//    $ff=zhongjiang_fanyi($dejiang);
    return $dejiang;
}
//中奖方式翻译
//$dejiang
function zhongjiang_fanyi($dejiang){
    $ff=['1'=>'庄','2'=>'闲','3'=>'和',
        '4'=>'庄对','5'=>'闲对','6'=>'对子','7'=>'三宝'
    ];
    $fy='';
    foreach ($dejiang as $v){
        $fy.=$ff[$v].',';
    }
    $fy= trim($fy,',');
    return $fy;
}
//中奖方式翻译(龙虎)
//$dejiang
function zhongjiang_lh_fanyi($dejiang){
    $ff=['1'=>'龙','2'=>'虎','3'=>'和'];


    return $ff[$dejiang];
}
//下注类型翻译
//$jingcai_zi
function jingcai_zi_fanyi($jingcai_zi='1',$re='v'){
    $a=[
        '1'=>'庄','2'=>'闲','3'=>'和',
        '4'=>'庄对','5'=>'闲对',
        '6'=>'对子','7'=>'三宝',
        '21'=>'梭哈庄','22'=>'梭哈闲','23'=>'梭哈和',/*'24'=>'梭哈对子','25'=>'梭哈三宝',*/'26'=>'梭哈庄对','27'=>'梭哈闲对',
    ];

    if ('v'==$re){
        return $a[$jingcai_zi];
    }else{
        $isin = array_search($jingcai_zi,$a);//在数组中搜索键值 $a，并返回它的键名：
        return $isin;
    }

}
//下注类型翻译()
//$jingcai_zi
function jingcai_zi_lh_fanyi($jingcai_zi='1',$re='v'){
    $a=[
        '1'=>'龙','2'=>'虎','3'=>'和',
    ];
    if ('v'==$re){
        return $a[$jingcai_zi];
    }else{
        $isin = array_search($jingcai_zi,$a);//在数组中搜索键值 $a，并返回它的键名：
        return $isin;
    }

}
/*
 * 下注代码
 */
function xiazhu_daima($xiazhu='庄'){
    $a=[
        '庄'=>'1','闲'=>'2','和'=>'3',
        '庄对'=>'4','闲对'=>'5',
        '对子'=>'6','三宝'=>'7',
        '梭哈庄'=>'1','梭哈闲'=>'2','梭哈和'=>'3',/*'24'=>'梭哈对子','25'=>'梭哈三宝',*/'梭哈庄对'=>'4','梭哈闲对'=>'5',

        '龙'=>'1','虎'=>'2',
        '梭哈龙'=>'1','梭哈虎'=>'2',
    ];
    return $a[$xiazhu];
}
/*
 * 生成二维码
 * */
function qrcode($url,$level=3,$size=4){
	Vendor('phpqrcode.phpqrcode');
	$errorCorrectionLevel =intval($level) ;//容错级别 
	$matrixPointSize = intval($size);//生成图片大小 
		//生成二维码图片 
	//echo $_SERVER['REQUEST_URI'];
	$object = new \QRcode();
	
	$date = date('Y-m-d');
	$path = "Uploads/qrcode/".$date.'/';
	if (!file_exists($path)) {
        mkdir ("$path", 0777, true);
	}
	$name = time().'_'.mt_rand();
    //生成的文件名
    $fileName = $path.$name.'.png';
	$res = $object->png($url, $fileName, $errorCorrectionLevel, $matrixPointSize, 2); 
	return $fileName;  
 }

/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function & load_wechat($type = '') {
	!class_exists('Wechat\Loader', FALSE) && Vendor('Wechat.Loader');
	static $wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
		// 从数据库查询配置参数
		$res = C('WEIXINPAY_CONFIG');
		$config['appid'] = $res['APPID'];
		$config['appsecret'] = $res['APPSECRET'];
		$config['encodingaeskey'] = '';
		$config['mch_id'] = $res['MCHID'];
		$config['partnerkey'] = $res['KEY'];
		$config['ssl_cer'] = '';
		$config['ssl_key'] = '';
		$config['cachepath'] = '';
		
		// 设置SDK的缓存路径
		$config['cachepath'] = CACHE_PATH . 'Data/';
		$wechat[$index] = &\Wechat\Loader::get_instance($type, $config);
	}
	return $wechat[$index];
}

//计算所有用户的流水并加入表
function user_liusui($t_id=1)
{
    $member = M('user');

    if ($t_id==0){
        //列出所有用户
        $list = $member->select();
    }else{
        //列出某代理用户
        $list = $member->where(['t_id'=>$t_id])->select();
    }

    foreach ($list as $k=>$v){
        $user_order = M("order")->field("sum(del_points) as sum_del")->where("userid={$v['id']} && state=1  && is_add=1 ")->find();
        if ($user_order['sum_del']){
            $data['liushui']=$user_order['sum_del'];
            M('user')->where("id={$v['id']}")->save($data);
        }
    }
}
//计算所有用户的流水并加入表
function user_liusui2($t_id=1,$map=[])
{
    $member = M('user');

    if ($t_id==0){
        //列出所有用户
        $list = $member->select();
    }else{
        //列出某代理用户
        $list = $member->where(['t_id'=>$t_id])->select();
    }
    foreach ($list as $k=>$v){
        $map['userid']=$v['id'];
        $map['state']=1;
        $map['is_add']=1;
        $user_order = M("order")->field("sum(del_points) as sum_del")->where($map)->find();

        if ($user_order['sum_del']){
            $data['liushui']=$user_order['sum_del'];
            M('user')->where("id={$v['id']}")->save($data);
        }
    }
}







//机器人频率换算
function robot_pinlv(){
   $robot= C('robot_rate');
   $pinlv=0;//机器人出手间隔（s）
    switch ($robot) {
        case "1":
            $pinlv=45;
            break;
        case "2":
            $pinlv=35;
            break;
        case "3":
            $pinlv=25;
            break;
        case "4":
            $pinlv=10;
            break;
        case "5":
            $pinlv=5;
            break;
        default:
            $pinlv=25;
    }
    
    return $pinlv;
}
?>